<template>
	<view class="publishDemand">
		<view class="publishDemand-content">
			<view class="formLabel uni-flex border-bottom bankCode" @click='showAvatarPopup'>
				<text>头像</text>
				<view class="uni-flex uni-align-center">
					<view class="avatar-container">
						<image v-if="userInfoEdit.avatar" :src="userInfoEdit.avatar" class="avatar-image"></image>
						<view v-else class="avatar-placeholder"></view>
					</view>
					<uni-icons type="right" size="15" style="margin-left:16rpx;" color="#666666"></uni-icons>
				</view>
			</view>
			<!-- 头像修改弹窗 -->
			<uni-popup ref="AvatarPopup" background-color="#fff" type="bottom">
				<view class="avatar-popup-content">
					<view class="avatar-popup-options">
						<view class="avatar-popup-option" @click="chooseImage('camera')">拍照</view>
						<view class="avatar-popup-option" @click="chooseImage('album')">从相册选择</view>
						<view class="avatar-popup-option cancel" @click="closeAvatarPopup">取消</view>
					</view>
				</view>
			</uni-popup>

			<!-- 其他表单内容保持不变 -->
			<view class="formLabel uni-flex border-bottom bankCode">
				<text>零付ID</text>
				<view class="uni-flex uni-align-center">
					<view class="slectBank">{{userInfoEdit.zeroId}}</view>
				</view>
			</view>
			<view class="formLabel uni-flex uni-align-center uni-justify-between border-bottom">
				<text>昵称</text>
				<view class="uni-flex uni-align-center">
					<input class="custom-input" placeholder="输入昵称" v-model="userInfoEdit.nikeName" />
					<uni-icons type="right" size="15" style="margin-left:16rpx;" color="#666666"></uni-icons>
				</view>
			</view>
			<view class="formLabel uni-flex uni-align-center uni-justify-between border-bottom"
				@click='showGenderPopup'>
				<text>性别</text>
				<view class="uni-flex uni-align-center">
					<view class="slectBank" :class="{ 'placeholder-text': !userInfoEdit.sex }">
						{{
					    userInfoEdit.sex === 0 || userInfoEdit.sex === '0' ? '男' :
					    userInfoEdit.sex === 1 || userInfoEdit.sex === '1' ? '女' :
					    userInfoEdit.sex === 2 || userInfoEdit.sex === '2' ? '未知' : '请选择性别'
					  }}
					</view>
					<uni-icons type="right" size="15" style="margin-left:16rpx;" color="#666666"></uni-icons>
				</view>
			</view>
			<!-- 性别弹窗组件 -->
			<uni-popup ref="genderPopup" background-color="#fff" type="bottom">
				<view class="popup-content">
					<radio-group @change="onGenderChange" class='popup-box'>
						<label>
							<radio value="男" :checked="userInfoEdit.sex === 0" /> 男
						</label>
						<label>
							<radio value="女" :checked="userInfoEdit.sex === 1" /> 女
						</label>
						<label>
							<radio value="未知" :checked="userInfoEdit.sex === 2" /> 未知
						</label>
					</radio-group>
				</view>
			</uni-popup>
			<view class="formLabel uni-flex uni-align-center uni-justify-between border-bottom">
				<text>年龄</text>
				<view class="uni-flex uni-align-center">
					<uni-datetime-picker v-model="userInfoEdit.birth" type="date" :clear-icon="true">
						<view class="slectBank" :class="{ 'placeholder-text': !userInfoEdit.birth }">
							{{ userInfoEdit.birth ? calculateAge(userInfoEdit.birth) : '选择出生年月日' }}
							<uni-icons type="right" size="15" style="margin-left:16rpx;" color="#666666"></uni-icons>
						</view>

					</uni-datetime-picker>
				</view>
			</view>
			<view class="formLabel uni-flex uni-align-center uni-justify-between border-bottom" @click="CitySelect">
				<text>户籍</text>
				<view class="uni-flex uni-align-center">
					<uni-data-picker placeholder="请选择户籍" popup-title="请选择所在地区" :localdata="dataTree"
						v-model="userInfoEdit.address" @change="onAddressChange" @nodeclick="onNodeClick">
					</uni-data-picker>
				</view>
			</view>
			<view class="formLabel uni-flex uni-align-center uni-justify-between" @click='goBrief'>
				<text>简介</text>
				<view class="uni-flex uni-align-center">
					<view class="briefIntroduction">{{userInfoEdit.remark}}</view>
					<uni-icons type="right" size="15" style="margin-left:16rpx;" color="#666666"></uni-icons>
				</view>
			</view>

		</view>
		<view class="publishDemand-button" @click="saveUserInfo">保存</view>
	</view>
</template>

<script setup>
	import CustomNavBar from "@/components/custom-navbar/index.vue";
	import {
		domicileAddressApi,
		editUserInfoApi
	} from '@/api/personalData.js'
	import {
		onShow
	} from '@dcloudio/uni-app';
	import {
		useStore
	} from 'vuex';
	import {
		computed,
		onMounted,
		ref
	} from "vue";
	import {
		qiNiuFileUpload
	} from '@/utils/qiniu.js'; // 根据实际路径调整
	const store = useStore();
	// 使用computed从Vuex中获取userInfo
	const userInfo = computed(() => store.state.userInfo || {});
	const genderPopup = ref(null);
	const AvatarPopup = ref(null);
	const dataTree = ref();
	const selectedAddress = ref([]); // 用于存储选中的各级地址
	const tempAvatarPath = ref(""); // 存储临时头像路径
	const userInfoEdit = ref({
		avatar: "",
		zeroId: "",
		nikeName: "",
		sex: "",
		birth: "",
		remark: "",
		address: ""
	});

	// 在个人信息页面的 script setup 中添加
	const updateRemark = (remark) => {
		userInfoEdit.value.remark = remark;
	};

	const calculateAge = (birthDate) => {
		if (!birthDate) return '';

		const today = new Date();
		const birth = new Date(birthDate);

		let age = today.getFullYear() - birth.getFullYear();
		const monthDiff = today.getMonth() - birth.getMonth();

		if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
			age--;
		}

		return age + '岁';
	};


	// 暴露方法到组件实例
	defineExpose({
		updateRemark
	});

	// 户籍选择
	const onAddressChange = (e) => {

	};

	// 节点点击事件
	const onNodeClick = (node) => {
		console.log('节点点击:', node);
		// 可以在这里处理点击逻辑，如果需要的话
	};

	const showGenderPopup = (() => {
		genderPopup.value.open();
	});
	const closeGenderPopup = (() => {
		genderPopup.value.close();
	});

	const showAvatarPopup = (() => {
		AvatarPopup.value.open();
	});

	const closeAvatarPopup = (() => {
		AvatarPopup.value.close();
	});

	const onGenderChange = ((e) => {
		const genderMap = {
			'男': 0,
			'女': 1,
			'未知': 2
		};
		userInfoEdit.value.sex = genderMap[e.detail.value] ?? 2;
		closeGenderPopup();
	});

	const maskClick = ((e) => {
		console.log('年龄', e);
	});

	// 保存用户信息
	const saveUserInfo = async () => {
		if (!userInfoEdit.value.nikeName) {
			uni.showToast({
				title: '请输入昵称',
				icon: 'none'
			});
			return;
		}

		try {
			uni.showLoading({
				title: '保存中...',
				mask: true
			});

			// 1. 只有选择了新头像时才上传
			if (tempAvatarPath.value) {
				const avatarUrl = await uploadAvatarToQiNiu();
				userInfoEdit.value.avatar = avatarUrl;
			}

			// 2. 保存用户信息
			const res = await editUserInfoApi(userInfoEdit.value);

			if (res.code === 200) {
				// 更新Vuex
				store.commit('setUserInfo', {
					...res.data
				});

				uni.setStorageSync('user_info', res.data);

				uni.showToast({
					title: res.msg||'修改成功！',
					icon: ''
				});

				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			} else {
				throw new Error(res.message || '接口错误');
			}
		} catch (error) {
			console.error('保存失败', error);
			uni.showToast({
				title: res.msg||'保存失败！',
				icon: 'error'
			});
		} finally {
			uni.hideLoading();
		}
	};
	const goBrief = (() => {
		uni.navigateTo({
			url: `/pages/personalCenter/userDetail/briefIntroduction?remark=${encodeURIComponent(userInfoEdit.value.remark || '')}`,
			events: {
				updateRemark: (data) => {
					if (data && data.remark !== undefined) {
						userInfoEdit.value.remark = data.remark;
					}
				}
			},
			success: (res) => {
				// 可以在这里获取事件通道，但新方式更推荐上面的事件定义方式
				console.log('111111111', res);
			}
		});
	});

	// 拍照或选择图片
	const chooseImage = (type) => {
		console.log('选择类型:', type);

		// 关闭弹窗
		closeAvatarPopup();

		// 检查相机权限
		if (type === 'camera') {
			checkCameraPermission().then(() => {
				openCamera();
			}).catch(err => {
				console.log('相机权限检查失败:', err);
				uni.showToast({
					title: '无法访问相机',
					icon: 'none'
				});
			});
		} else {
			openAlbum();
		}
	};
	// 检查相机权限
	const checkCameraPermission = () => {
		return new Promise((resolve, reject) => {
			uni.authorize({
				scope: 'scope.camera',
				success: resolve,
				fail: (err) => {
					// 如果用户拒绝了授权，引导去设置页
					if (err.errMsg.includes('auth deny')) {
						uni.showModal({
							title: '提示',
							content: '需要相机权限才能拍照，是否去设置开启权限？',
							success: (res) => {
								if (res.confirm) {
									uni.openSetting();
								}
							}
						});
					}
					reject(err);
				}
			});
		});
	};

	// 打开相机拍照
	const openCamera = () => {
		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'], // 压缩图
			sourceType: ['camera'], // 相机
			camera: 'front', // 前置或后置摄像头，可选 'front'/'back'
			success: (res) => {
				handleImageSuccess(res.tempFilePaths[0]);
			},
			fail: (err) => {
				console.error('拍照失败:', err);
				uni.showToast({
					title: '拍照失败',
					icon: 'none'
				});
			}
		});
	};

	// 打开相册选择
	const openAlbum = () => {
		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'], // 压缩图
			sourceType: ['album'], // 相册
			success: (res) => {
				handleImageSuccess(res.tempFilePaths[0]);
			},
			fail: (err) => {
				console.error('选择图片失败:', err);
				uni.showToast({
					title: '选择图片失败',
					icon: 'none'
				});
			}
		});
	};

	// 处理图片选择成功
	const handleImageSuccess = (tempFilePath) => {
		if (tempFilePath) {
			// 显示加载中
			uni.showLoading({
				title: '处理中...',
				mask: true
			});

			// 保存临时路径
			tempAvatarPath.value = tempFilePath;
			userInfoEdit.value.avatar = tempFilePath;

			// 可以在这里添加图片压缩处理
			compressImage(tempFilePath).then(compressedPath => {
				userInfoEdit.value.avatar = compressedPath;
				uni.hideLoading();
			}).catch(err => {
				console.log('压缩失败，使用原图', err);
				uni.hideLoading();
			});
		}
	};

	// 图片压缩
	const compressImage = (src) => {
		return new Promise((resolve, reject) => {
			uni.compressImage({
				src,
				quality: 70, // 压缩质量
				success: (res) => {
					resolve(res.tempFilePath);
				},
				fail: reject
			});
		});
	};
	// 上传头像到七牛云
	const uploadAvatarToQiNiu = async () => {
		if (!tempAvatarPath.value) {
			// 如果没有新头像，直接返回原有的 avatar 值
			// 确保返回的格式是 images/avatar/userId/timestamp_random.png
			return userInfoEdit.value.avatar;
		}

		const userId = userInfo.value.id || 'defaultUserId';
		const timestamp = Date.now();
		const random = Math.floor(Math.random() * 10);
		const key = `images/avatar/${userId}/${timestamp}_${random}.png`;

		const files = [{
			path: tempAvatarPath.value,
			key: key
		}];

		return new Promise((resolve, reject) => {
			qiNiuFileUpload(files,
				(successUrl) => {
					console.log('七牛返回URL', successUrl);
					// 确保返回的是单个URL（如果是多个用逗号分隔的，取第一个）
					const avatarUrl = successUrl.split(',')[0];
					resolve(avatarUrl);
				},
				(error) => {
					console.error('七牛上传失败', error);
					reject(error);
				}
			);
		});
	};

	// 页面加载时检查用户信息
	onMounted(() => {
		domicileAddressApi().then((res) => {
			if (res.code === 200) {
				dataTree.value = res.data;
			}
		});

		console.log('从Vuex获取的用户信息:', userInfo.value);
		if (userInfo.value && Object.keys(userInfo.value).length > 0) {
			Object.keys(userInfoEdit.value).forEach(key => {
				if (userInfo.value.hasOwnProperty(key)) {
					// 特殊处理 sex 字段
					if (key === 'sex') {
						const sexValue = userInfo.value[key];
						if (sexValue === '男' || sexValue === '0') {
							userInfoEdit.value[key] = 0;
						} else if (sexValue === '女' || sexValue === '1') {
							userInfoEdit.value[key] = 1;
						} else if (sexValue === '未知' || sexValue === '2') {
							userInfoEdit.value[key] = 2;
						} else {
							userInfoEdit.value[key] = typeof sexValue === 'number' ? sexValue : 2;
						}
					} else {
						// 其他字段直接赋值
						userInfoEdit.value[key] = userInfo.value[key];
					}
				}
			});

			// 确保 avatar 字段有值且格式正确
			if (!userInfoEdit.value.avatar) {
				const userId = userInfo.value.id || 'defaultUserId';
				const timestamp = Date.now();
				const random = Math.floor(Math.random() * 10);
				userInfoEdit.value.avatar = `images/avatar/${userId}/${timestamp}_${random}.png`;
			}
		}
	});
</script>

<style scoped lang="scss">
	.publishDemand {
		padding: 26rpx 24rpx 81rpx;
		background: #F5F5F5;
		min-height: calc(100vh - 26rpx);

		.subtitle {
			font-weight: 400;
			font-size: 24rpx;
			color: #666666;
			margin: 32rpx 0 24rpx;
		}

		.publishDemand-content {
			background: #FFFFFF;
			border-radius: 20rpx;
			padding: 0 26rpx 0 23rpx;
			margin-top: 44rpx;

			.border-bottom {
				border-bottom: 1px solid #E2E2E2;
			}

			.formLabel {
				padding: 24rpx 0;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.slectBank {
					font-weight: 400;
					font-size: 28rpx;
					color: #999999;
					display: flex;
					flex-wrap: wrap;
				}

				.briefIntroduction {
					font-weight: 400;
					font-size: 28rpx;
					color: #999999;
					display: flex;
					flex-wrap: wrap;
					white-space: normal;
					word-wrap: break-word;
					word-break: break-all;
					max-width: 400rpx;
				}

				text {
					font-weight: 500;
					font-size: 28rpx;
					color: #303133;
					line-height: 70rpx;
				}

				.avatar-container {
					width: 80rpx;
					height: 80rpx;
					border-radius: 50%;
					overflow: hidden;

					.avatar-image {
						width: 100%;
						height: 100%;
					}

					.avatar-placeholder {
						width: 100%;
						height: 100%;
						background-color: #f0f0f0;
						border-radius: 50%;
					}
				}
			}
		}

		.publishDemand-button {
			width: 100%;
			height: 88rpx;
			background: #2F80ED;
			border-radius: 44rpx;
			text-align: center;
			font-weight: 400;
			font-size: 28rpx;
			color: #FFFFFF;
			line-height: 88rpx;
			margin: 40rpx auto 0;
		}
	}

	/* 头像弹窗样式 */
	.avatar-popup-content {
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 999;
		height: 360rpx;

		.avatar-popup-options {
			background-color: #fff;
			border-radius: 24rpx 24rpx 0 0;
			overflow: hidden;
			height: 100%;

			.avatar-popup-option {
				padding: 30rpx 0;
				text-align: center;
				font-size: 32rpx;
				color: #333;
				border-bottom: 1rpx solid #f0f0f0;

				&:active {
					background-color: #f9f9f9;
				}

				&.cancel {
					margin-top: 20rpx;
					border-radius: 0 0 24rpx 24rpx;
					border-bottom: none;
					color: #ff3b30;
					background-color: #fff;
				}
			}
		}
	}

	.popup-content {
		background-color: #fff;
		padding: 20rpx;
		height: 315rpx;

		.popup-box {
			height: 100%;
			display: flex;
			flex-direction: column;
			justify-content: space-evenly;
			align-items: center;
		}
	}

	.custom-input {
		color: #999;
		font-size: 28rpx;
		font-weight: 400;
		text-align: right;
		/* 确保文本右对齐 */
		width: 100%;
		/* 确保宽度填满容器 */
		padding: 0;
		/* 清除可能的内边距 */
		margin: 0;
		/* 清除可能的外边距 */
		flex: 1;
		/* 在flex布局中占据剩余空间 */
	}

	::v-deep .input-value-border {
		border: none !important;
	}

	::v-deep .text-color {
		color: #999 !important;
	}

	::v-deep .placeholder {
		font-size: 28rpx;
	}

	.placeholder-text {
		color: #999 !important;
	}
</style>